import { defineStore } from 'pinia'
import router from '../router'
import { findPrmissionList } from '../api/permissionMenu.js'

let modules = import.meta.glob('../views/**/*.vue')
const useUserStore = defineStore('user', {
  state: () => ({
    userNameKey: 'USER_NAME',
    tokenKey: 'TOKEN',
    endPathKey: 'END_PATH',
    routes: [],
    user: {
      username: undefined,
      token: undefined,
    },
    tabs: {
      menus: [],
      activeName: 'home',
    },
  }),
  actions: {
    saveUser(username, token) {
      this.user.username = username
      this.user.token = token
      sessionStorage.setItem(this.userNameKey, username)
      sessionStorage.setItem(this.tokenKey, token)
      router.push('/index')
    },
    async loadRouter() {
      await findPrmissionList().then((result) => {
        console.log('路由集合', result)
        let endPath = sessionStorage.getItem(this.endPathKey)
        this.routes = result.data
        for (let route of result.data) {
          if (route.component) {
            route.component = modules[`../views${route.component}.vue`]
          }
          router.addRoute(route.parentName, route)
          if (endPath && route.path == endPath) {
            this.addTab(route)
          }
        }
      })
      return 'success'
    },
    addTab(menu) {
      let currentMenu = this.tabs.menus.find((item) => menu.name == item.name)
      this.tabs.activeName = menu.name
      if (currentMenu) {
        return
      }
      this.tabs.menus.push(menu)
    },
    removeTab(tabName) {
      // 当前tab的下标
      let currentIndex = this.tabs.menus.findIndex(
        (item) => item.name == tabName,
      )
      this.tabs.menus = this.tabs.menus.filter((item) => item.name != tabName)
      if (tabName != this.tabs.activeName) {
        return
      }
      this.tabs.activeName = 'home'
      if (currentIndex != 0) {
        this.tabs.activeName = this.tabs.menus[currentIndex - 1].name
      } else if (currentIndex == 0) {
        sessionStorage.setItem(this.endPathKey, '/')
      }
      router.push({ name: this.tabs.activeName })
    },
  },
  getters: {
    getUser() {
      if (!this.user.username) {
        this.user.username = sessionStorage.getItem(this.userNameKey)
        this.user.token = sessionStorage.getItem(this.tokenKey)
      }
      return this.user
    },
  },
})

export default useUserStore
